/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.yug.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.yug.entity.YugCategory;
import com.thinkgem.jeesite.modules.yug.entity.YugCategoryVedioRef;
import com.thinkgem.jeesite.modules.yug.entity.YugVideo;
import com.thinkgem.jeesite.modules.yug.service.YugCategoryService;
import com.thinkgem.jeesite.modules.yug.service.YugCategoryVedioRefService;
import com.thinkgem.jeesite.modules.yug.service.YugVideoService;
import com.thinkgem.jeesite.modules.yug.utils.YugVideoUtils;

/**
 * 视频链接维护Controller
 * 
 * @author Jeff
 * @version 2016-12-04
 */
@Controller
@RequestMapping(value = "${adminPath}/yug/yugVideo")
public class YugVideoController extends BaseController {

	@Autowired
	private YugVideoService yugVideoService;
	@Autowired
	private YugCategoryService yugCategoryService;
	@Autowired
	private YugCategoryVedioRefService yugCategoryVedioRefService;
	
	@ModelAttribute
	public YugVideo get(@RequestParam(required = false) String id) {
		YugVideo entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = yugVideoService.get(id);
		}
		if (entity == null) {
			entity = new YugVideo();
		}
		return entity;
	}

	@RequiresPermissions("yug:yugVideo:view")
	@RequestMapping(value = { "list", "" })
	public String list(YugVideo yugVideo, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<YugVideo> page = yugVideoService.findPage(new Page<YugVideo>(request, response), yugVideo);
		model.addAttribute("page", page);
		return "modules/yug/yugVideoList";
	}

	@RequiresPermissions("yug:yugVideo:view")
	@RequestMapping(value = "form")
	public String form(YugVideo yugVideo, Model model) {
		List<YugCategory> categories = yugCategoryService.findList(new YugCategory());
		model.addAttribute("yugVideo", yugVideo);
		model.addAttribute("categories", categories);
		return "modules/yug/yugVideoForm";
	}

	@RequiresPermissions("yug:yugVideo:edit")
	@RequestMapping(value = "save")
	public String save(YugVideo yugVideo, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, yugVideo)) {
			return form(yugVideo, model);
		}
		yugVideoService.save(yugVideo);
		if(yugVideo.getCategory()!=null &&yugVideo.getCategory().getId()!=null){
			//save link
			YugCategoryVedioRef ref =new YugCategoryVedioRef();
			ref.setCategoryid(yugVideo.getCategory().getId());
			ref.setVedioid(yugVideo.getId());
			yugCategoryVedioRefService.save(ref);
		}
		addMessage(redirectAttributes, "保存视频信息维护成功");
		return "redirect:" + Global.getAdminPath() + "/yug/yugVideo/?repage";
	}

	@RequiresPermissions("yug:yugVideo:edit")
	@RequestMapping(value = "delete")
	public String delete(YugVideo yugVideo, RedirectAttributes redirectAttributes) {
		yugVideoService.delete(yugVideo);
		addMessage(redirectAttributes, "删除视频信息维护成功");
		return "redirect:" + Global.getAdminPath() + "/yug/yugVideo/?repage";
	}

	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("yug:yugVideo:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "视频数据导入模板.xlsx";
    		List<YugVideo> list = Lists.newArrayList(); list.add(YugVideoUtils.getDefaultVideo());
    		new ExportExcel("视频数据", YugVideo.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/yug/yugVideo/list?repage";
    }
	
	@RequiresPermissions("yug:yugVideo:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/yug/yugVideo/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<YugVideo> list = ei.getDataList(YugVideo.class);
			Map<String,YugCategory> nameIdMap= yugCategoryService.findMap();
			for (YugVideo video : list) {
				try {	
					YugCategory category = nameIdMap.get(video.getCategory().getName());
						if(!StringUtils.isBlank(video.getCategory().getName()) && category!=null){
							yugVideoService.save(video);
							//save link
							YugCategoryVedioRef ref =new YugCategoryVedioRef();
							
							ref.setCategoryid(category.getId());
							ref.setVedioid(video.getId());
							yugCategoryVedioRefService.save(ref);
							successNum++;
						}else{
							failureMsg.append("<br/>视频名" + video.getName() + " 导入失败：" +"不能识别的种类名");
							failureNum++;
						}
				} catch (ConstraintViolationException ex) {
					failureMsg.append("<br/>视频名" + video.getName() + " 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList) {
						failureMsg.append(message + "; ");
						failureNum++;
					}
				} catch (Exception ex) {
					ex.printStackTrace();
					failureMsg.append("<br/>视频名" + video.getName() + " 导入失败：" + ex.getMessage());
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条视频，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条视频" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入 视频失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/yug/yugVideo/list?repage";
	}
}